/**
 * Copyright (C) 2013 Daniel Gee.
 * See LICENSE.txt for more details.
 */
package com.rl.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Daniel Gee
 */
public class CollectionUtil
{
	/**
	 * Performs a linear search for the target specified across the array specified. Similar to
	 * {@link Arrays#binarySearch(Object[], Object)}, except that the array being searched doesn't
	 * have to be sorted. If the array given is <tt>null</tt> then <tt>false</tt> is always
	 * returned.
	 * 
	 * @param target
	 *            what to look for.
	 * @param array
	 *            the array to look in.
	 * @return if the element is within the array or not.
	 */
	@SafeVarargs
	public static <E> boolean linearSearch(E target, E... array)
	{
		if (array == null)
		{
			return false;
		}
		if (target == null)
		{
			for (E e : array)
			{
				if (e == null)
				{
					return true;
				}
			}
		}
		else
		{
			for (E e : array)
			{
				if (e.equals(target))
				{
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Makes a copy of the array given and shuffles it before returning it.
	 * 
	 * @param array
	 *            the array to make a shuffled copy of.
	 * @return a shuffled copy of the array specified.
	 */
	@SafeVarargs
	public static <E> E[] shuffled(E... array)
	{
		E[] arRet = Arrays.copyOf(array, array.length);
		List<E> schuffleList = Arrays.asList(arRet);
		Collections.shuffle(schuffleList);
		return arRet;
	}

	/**
	 * Returns the list of arguments as a {@link Set}. If the argument given is <tt>null</tt> or
	 * length 0, then an empty (but mutable) set is returned.
	 * 
	 * @param args
	 *            the objects to put into a set.
	 * @return the new Set.
	 */
	@SafeVarargs
	public static <E> Set<E> toSet(E... args)
	{
		Set<E> set = new HashSet<>();
		if (args == null)
		{
			return set;
		}
		for (E e : args)
		{
			set.add(e);
		}
		return set;
	}
}
